package cn.itsource.org.service.impl;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.service.BaseServiceImpl;
import cn.itsource.basic.util.*;
import cn.itsource.config.exception.CustomException;
import cn.itsource.org.Dto.rejectShopDto;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.org.service.IShopService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop, ShopQuery> implements IShopService {
    //因为事务都是在service层操作的
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisService redisService;

    /**
     * 店铺入驻
     * @param shop
     * @return
     */
    @Override
    @Transactional   //事务管理
    public AjaxResult settlement(Shop shop) {
        //1.新增员工到数据库
        Employee admin = shop.getAdmin(); //不带id
//        验证两次密码是否一致
        if (!StrUtil.equals(admin.getPassword(),admin.getComfirmPassword())){
            throw new RuntimeException("两次密码不一致!");
        }
        //1.1判断用户名，手机号，邮箱全部都不能重复,deduplication(去重)
        if( employeeService.accountingCheck(admin)!=null){
            throw new RuntimeException("用户名已被注册!");
        }
        if (employeeService.phoneCheck(admin)!=null){
            throw new RuntimeException("手机号已被注册!");
        }
        if (employeeService.emailCheck(admin)!=null){
            throw new RuntimeException("邮箱已被注册!");
        }

        /**
         * 加盐加密流程
         */
//        用uuid生成盐值
        String simpleUUID = IdUtil.fastSimpleUUID();
//        密码加盐基础上进行---Md5加密
        String pwd = MD5.create().setSalt(simpleUUID.getBytes()).digestHex(admin.getComfirmPassword());
//        入库
        admin.setSalt(simpleUUID);
        admin.setPassword(pwd);
        employeeService.save(admin);
        shop.setAdmin(admin);
        //3.新增店铺信息
        shopMapper.insertShop(shop);
        //4.拿到店铺的id，设置员工，修改员工
        admin.setShopId(shop.getId());
        employeeService.update(admin);
////        发送邮件
//        String uuid  = IdUtil.fastSimpleUUID();
////        用注入的邮件组件发送邮件
//        emailService.sendEMail("宠物乐园激活","审核通过,请在两个小时内激活,点击链接激活,http://localhost/shop/active/"+uuid+"/"+shop.getId(),admin.getEmail());
//        //5.1redis存数据 key:uuid  value：店铺id
//        redisService.setStringKeyAndValue(uuid,shop.getId(),120);
//        //直接返回成功，如果异常会走全局异常
        return AjaxResult.createSuccess();
    }
    //    邮件激活店铺
    @Override
    public AjaxResult active(String uuid, Long id) {
        //0.如果已经激活过了，告诉他不用再激活了
        Shop shop1 = shopMapper.selectByPrimaryKey(id);
        if (shop1 != null && shop1.getState() == PetConstant.Shop.STATE_ACTIVE_SUCCESS) {
            throw new RuntimeException("不要重复激活");
        }

        //1.从redis里面通过uuid获取店铺id
        String shopId = redisService.getKeyStringValue(uuid);
        if (StrUtil.isBlank(shopId)) {
            throw new RuntimeException("激活时间已经过了，请联系管理员");
        }
        //2.激活
        Shop shop = new Shop();
        shop.setId(Long.valueOf(shopId));
        shop.setState(PetConstant.Shop.STATE_ACTIVE_SUCCESS);
        //修改状态
        shopMapper.updateByPrimaryKeySelective(shop);

        return AjaxResult.createSuccess("恭喜你，激活成功，可以登录系统了");
    }
    @Override
    public PageList<Shop> findPageList(ShopQuery query) {
        //1.分页插件的使用
        PageHelper.startPage(query.getPage(), query.getSize());
        //2.执行分页语句 1，2顺序不能反  ，中间不能写代码
        List<Shop> list = shopMapper.findPageList(query);
        //3.封装到pageInfo里面去
        PageInfo<Shop> shopPageInfo = new PageInfo<>(list);
        //4.封装自定义pageList对象
        PageList<Shop> shopPageList = new PageList<>(shopPageInfo.getTotal(), shopPageInfo.getList());
        return shopPageList;
    }
//驳回申请
    @Override
    @Transactional
    public void reject(rejectShopDto dto) {
        shopMapper.reject(dto);
        //        发送邮件
        emailService.sendEMail("宠物乐园","非常抱歉您的申请暂不符合宠物乐园的激活要求,请整改后再次申请!\n驳回原因:\n"+dto.getCause());

    }

    //    修改店铺状态
    @Override
    @Transactional
    public void update(Shop shop){
        shopMapper.update(shop);
        //        发送邮件
        String uuid  = IdUtil.fastSimpleUUID();
//        用注入的邮件组件发送邮件
        emailService.sendEMail("宠物乐园激活","审核通过,请在两个小时内激活,点击链接激活,http://localhost/shop/active/"+uuid+"/"+shop.getId(),shop.getAdmin().getEmail());
        //5.1redis存数据 key:uuid  value：店铺id
        redisService.setStringKeyAndValue(uuid,shop.getId(),120);
    }
}
